package com.markus.code.图.图2;

import java.util.HashSet;
import java.util.Stack;

/**
 * Author:markusZhang
 * Date:Create in 2020/8/30 15:45
 * todo: 图的深度优先遍历
 */
public class GraphDfs {

    /**
     * 从node节点出发，完成深度优先遍历
     */
    public void dfs(Node node){
        Stack<Node> stack = new Stack<>();
        HashSet<Node> set = new HashSet<>();
        stack.push(node);
        set.add(node);
        //入栈就打印
        System.out.print(node.value+" ");
        while(!stack.isEmpty()){
            Node pop = stack.pop();
            for (Node nextNode : pop.nextNodes) {
                if (!set.contains(nextNode)){
                    stack.push(pop);
                    stack.push(nextNode);
                    System.out.print(nextNode.value+" ");
                    set.add(nextNode);
                    break;
                }
            }
        }
    }
}
